package com.cyy.springbootinit.controller;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyy.springbootinit.annotation.AuthCheck;
import com.cyy.springbootinit.common.BaseResponse;
import com.cyy.springbootinit.common.DeleteRequest;
import com.cyy.springbootinit.common.ErrorCode;
import com.cyy.springbootinit.common.ResultUtils;
import com.cyy.springbootinit.constant.UserConstant;
import com.cyy.springbootinit.exception.BusinessException;
import com.cyy.springbootinit.exception.ThrowUtils;
import com.cyy.springbootinit.model.dto.balanceAlarm.BalanceAlarmAddRequest;
import com.cyy.springbootinit.model.dto.balanceAlarm.BalanceAlarmEditRequest;
import com.cyy.springbootinit.model.dto.balanceAlarm.BalanceAlarmQueryRequest;
import com.cyy.springbootinit.model.dto.balanceAlarm.BalanceAlarmUpdateRequest;
import com.cyy.springbootinit.model.entity.BalanceAlarm;
import com.cyy.springbootinit.model.entity.User;
import com.cyy.springbootinit.model.vo.BalanceAlarmVO;
import com.cyy.springbootinit.service.BalanceAlarmService;
import com.cyy.springbootinit.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 余额报警记录表接口
 *
 * @author 程序员cyy</a>
 * @from cyy</a>
 */
@RestController
@RequestMapping("/balanceAlarm")
@Slf4j
public class BalanceAlarmController {

    @Resource
    private BalanceAlarmService balanceAlarmService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建余额报警记录表
     *
     * @param balanceAlarmAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addBalanceAlarm(@RequestBody BalanceAlarmAddRequest balanceAlarmAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(balanceAlarmAddRequest == null, ErrorCode.PARAMS_ERROR);
        // todo 在此处将实体类和 DTO 进行转换
        BalanceAlarm balanceAlarm = new BalanceAlarm();
        BeanUtils.copyProperties(balanceAlarmAddRequest, balanceAlarm);
        // 数据校验
        balanceAlarmService.validBalanceAlarm(balanceAlarm, true);
        // todo 填充默认值
        balanceAlarm.setAlarmDate(new DateTime());
        // 写入数据库
        boolean result = balanceAlarmService.save(balanceAlarm);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newBalanceAlarmId = balanceAlarm.getId();
        return ResultUtils.success(newBalanceAlarmId);
    }

    /**
     * 删除余额报警记录表
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteBalanceAlarm(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        BalanceAlarm oldBalanceAlarm = balanceAlarmService.getById(id);
        ThrowUtils.throwIf(oldBalanceAlarm == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if ( !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = balanceAlarmService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新余额报警记录表（仅管理员可用）
     *
     * @param balanceAlarmUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateBalanceAlarm(@RequestBody BalanceAlarmUpdateRequest balanceAlarmUpdateRequest) {
        if (balanceAlarmUpdateRequest == null || balanceAlarmUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        BalanceAlarm balanceAlarm = new BalanceAlarm();
        BeanUtils.copyProperties(balanceAlarmUpdateRequest, balanceAlarm);
        // 数据校验
        balanceAlarmService.validBalanceAlarm(balanceAlarm, false);
        // 判断是否存在
        long id = balanceAlarmUpdateRequest.getId();
        BalanceAlarm oldBalanceAlarm = balanceAlarmService.getById(id);
        ThrowUtils.throwIf(oldBalanceAlarm == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = balanceAlarmService.updateById(balanceAlarm);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取余额报警记录表（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<BalanceAlarmVO> getBalanceAlarmVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        BalanceAlarm balanceAlarm = balanceAlarmService.getById(id);
        ThrowUtils.throwIf(balanceAlarm == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(balanceAlarmService.getBalanceAlarmVO(balanceAlarm, request));
    }

    /**
     * 分页获取余额报警记录表列表（仅管理员可用）
     *
     * @param balanceAlarmQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<BalanceAlarm>> listBalanceAlarmByPage(@RequestBody BalanceAlarmQueryRequest balanceAlarmQueryRequest) {
        long current = balanceAlarmQueryRequest.getCurrent();
        long size = balanceAlarmQueryRequest.getPageSize();
        System.out.println("balanceAlarmQueryRequest.getDormitoryId()"+balanceAlarmQueryRequest.getDormitoryId());
        // 查询数据库
        Page<BalanceAlarm> balanceAlarmPage = balanceAlarmService.page(new Page<>(current, size),
                balanceAlarmService.getQueryWrapper(balanceAlarmQueryRequest));
        return ResultUtils.success(balanceAlarmPage);
    }

    //根据宿舍id查找报警记录的数量
    @GetMapping("/get/count")
    public BaseResponse<Long> getBalanceAlarmCountByDormitoryId(@RequestParam Integer dormitoryId){
        return ResultUtils.success(balanceAlarmService.getBalanceAlarmCountByDormitoryId(dormitoryId));
    }
    /**
     * 分页获取余额报警记录表列表（封装类）
     *
     * @param balanceAlarmQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<BalanceAlarmVO>> listBalanceAlarmVOByPage(@RequestBody BalanceAlarmQueryRequest balanceAlarmQueryRequest,
                                                               HttpServletRequest request) {
        long current = balanceAlarmQueryRequest.getCurrent();
        long size = balanceAlarmQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<BalanceAlarm> balanceAlarmPage = balanceAlarmService.page(new Page<>(current, size),
                balanceAlarmService.getQueryWrapper(balanceAlarmQueryRequest));
        // 获取封装类
        return ResultUtils.success(balanceAlarmService.getBalanceAlarmVOPage(balanceAlarmPage, request));
    }

    /**
     * 分页获取当前登录用户创建的余额报警记录表列表
     *
     * @param balanceAlarmQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<BalanceAlarmVO>> listMyBalanceAlarmVOByPage(@RequestBody BalanceAlarmQueryRequest balanceAlarmQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(balanceAlarmQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        long current = balanceAlarmQueryRequest.getCurrent();
        long size = balanceAlarmQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<BalanceAlarm> balanceAlarmPage = balanceAlarmService.page(new Page<>(current, size),
                balanceAlarmService.getQueryWrapper(balanceAlarmQueryRequest));
        // 获取封装类
        return ResultUtils.success(balanceAlarmService.getBalanceAlarmVOPage(balanceAlarmPage, request));
    }

    /**
     * 编辑余额报警记录表（给用户使用）
     *
     * @param balanceAlarmEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editBalanceAlarm(@RequestBody BalanceAlarmEditRequest balanceAlarmEditRequest, HttpServletRequest request) {
        if (balanceAlarmEditRequest == null || balanceAlarmEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        BalanceAlarm balanceAlarm = new BalanceAlarm();
        BeanUtils.copyProperties(balanceAlarmEditRequest, balanceAlarm);
        // 数据校验
        balanceAlarmService.validBalanceAlarm(balanceAlarm, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = balanceAlarmEditRequest.getId();
        BalanceAlarm oldBalanceAlarm = balanceAlarmService.getById(id);
        ThrowUtils.throwIf(oldBalanceAlarm == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = balanceAlarmService.updateById(balanceAlarm);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    // endregion
}
